package com.tech.cloudapp.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tech.cloudapp.biz.service.IBUserService;
import com.tech.cloudapp.db.entity.UserInfo;
import com.tech.cloudapp.db.service.UserInfoService;
import com.tech.cloudapp.exception.BusinessException;
import com.tech.cloudapp.model.CommonResponseDO;
import com.tech.cloudapp.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Primary
@Service
public class BUserServiceImpl implements IBUserService {

    @Autowired
    private UserInfoService userInfoServiceImpl;

    @Transactional
    @Override
    public String register(UserInfo userInfo) throws BusinessException {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userInfo.getUserId());
        UserInfo u = userInfoServiceImpl.getOne(queryWrapper);
        if(u == null)
        {
            userInfoServiceImpl.save(userInfo);
            //throw new BusinessException(CommonResponseDO.builder(0,"用户已存在"));
        }

        return getToken(userInfo.getUserId());
        //返回auth

    }

    @Override
    public int vaildate(UserInfo userInfo) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userInfo.getUserId());
        UserInfo u = userInfoServiceImpl.getOne(queryWrapper);
        if(u == null)
        {
            return 0;
        }else
        {
            return 1;
        }
    }

    @Override
    public String getToken(String userId) throws BusinessException {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        UserInfo u = userInfoServiceImpl.getOne(queryWrapper);
        if(u == null)
        {
            throw new BusinessException(CommonResponseDO.builder(0,"用户不存在"));
        }

        return JwtUtil.generateToken(userId);
    }

    @Override
    public void update(UserInfo userInfo) throws BusinessException {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userInfo.getUserId());
        boolean success = userInfoServiceImpl.update(userInfo,queryWrapper);
        if(!success)
        {
            throw new BusinessException(CommonResponseDO.builder(0,"用户数据更新失败"));
        }

    }


}
